package cn.iocoder.yudao.module.erp.service.business.group.suppliergroup;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.erp.controller.admin.business.group.suppliergroup.vo.SupplierGroupPageReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.business.group.suppliergroup.vo.SupplierGroupSaveReqVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.business.group.suppliergroup.SupplierGroupDO;
import cn.iocoder.yudao.module.erp.dal.mysql.business.group.suppliergroup.SupplierGroupMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.SUPPLIER_GROUP_NOT_EXISTS;

/**
 * 供应商分组 Service 实现类
 *
 * @author maxuxu
 */
@Service
@Validated
public class SupplierGroupServiceImpl implements SupplierGroupService {

    @Resource
    private SupplierGroupMapper supplierGroupMapper;

    @Override
    public Long createSupplierGroup(SupplierGroupSaveReqVO createReqVO) {
        // 插入
        SupplierGroupDO supplierGroup = BeanUtils.toBean(createReqVO, SupplierGroupDO.class);
        supplierGroupMapper.insert(supplierGroup);
        // 返回
        return supplierGroup.getId();
    }

    @Override
    public void updateSupplierGroup(SupplierGroupSaveReqVO updateReqVO) {
        // 校验存在
        validateSupplierGroupExists(updateReqVO.getId());
        // 更新
        SupplierGroupDO updateObj = BeanUtils.toBean(updateReqVO, SupplierGroupDO.class);
        supplierGroupMapper.updateById(updateObj);
    }

    @Override
    public void deleteSupplierGroup(Long id) {
        // 校验存在
        validateSupplierGroupExists(id);
        // 删除
        supplierGroupMapper.deleteById(id);
    }

    private void validateSupplierGroupExists(Long id) {
        if (supplierGroupMapper.selectById(id) == null) {
            throw exception(SUPPLIER_GROUP_NOT_EXISTS);
        }
    }

    @Override
    public SupplierGroupDO getSupplierGroup(Long id) {
        return supplierGroupMapper.selectById(id);
    }

    @Override
    public PageResult<SupplierGroupDO> getSupplierGroupPage(SupplierGroupPageReqVO pageReqVO) {
        return supplierGroupMapper.selectPage(pageReqVO);
    }

    @Override
    public List<SupplierGroupDO> getSupplierList() {
        return supplierGroupMapper.selectList();
    }

}